import { useState } from "react";
import {
  RecoilRoot,
  atom,
  useRecoilState,
  selector,
  useRecoilValue,
  useSetRecoilState
} from "recoil";

// 1. 一个 atom 代表一个状态。Atom 可在任意组件中进行读写。读取 atom 值的组件隐式订阅了该 atom，因此任何 atom 的更新都将导致订阅该 atom 的组件重新渲染：
const listState = atom({
  key: "list", // 全局唯一
  default: [], // 默认值
});
// 3. selector 代表一个派生状态，派生状态是状态的转换。你可以将派生状态视为将状态传递给以某种方式修改给定状态的纯函数的输出
const charCountState = selector({
  key: "charCountState", // unique ID (with respect to other atoms/selectors)
  get: ({ get }) => {
    const list = get(listState);

    return list.length;
  },
});

function Todo() {
  // 2. 在需要向 atom 读取或写入的组件中，应该使用 useRecoilState()
  const [list, setList] = useRecoilState(listState);
  const [text, setText] = useState("");
  const handleKeyUp = (event) => {
    // console.log(event.code);
    if (event.code === "Enter") {
      setList([...list, text]);
    }
  };
  return (
    <div>
      <input
        value={text}
        onChange={(event) => setText(event.target.value)}
        onKeyUp={handleKeyUp}
      ></input>
      <button onClick={() => setList([...list, text])}> 增加 </button>
      <ul>
        {list.map((item, index) => (
          <li key={index}> {item} </li>
        ))}
      </ul>
    </div>
  );
}

function Count() {
  const list = useRecoilValue(listState);
  const count = useRecoilValue(charCountState);

  const setList = useSetRecoilState(listState);
  const [todoList, setTodoList] = useRecoilState(listState);
  return (
    <div>
      {count}-{list.length}-{todoList.length}
    </div>
  );
}

export default function App() {
  return (
    // 0. 根组件
    <RecoilRoot>
      <Todo />
      <Count />
    </RecoilRoot>
  );
}
